package com.example.redissiontest.service;

import com.example.redissiontest.config.DistributedLock;
import com.example.redissiontest.config.DistributedLockParam;
import com.example.redissiontest.entity.Ticket;
import com.example.redissiontest.repository.TicketRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author Lay
 * @description
 * @date 2023年04月23日 20:50
 */
@Service
@RequiredArgsConstructor
public class TicketService {
    private final TicketRepository ticketRepository;


    @DistributedLock(value = "ticket",waitTime = 1,leaseTime = 2,timeUnit = TimeUnit.SECONDS)
    public Long deduct(@DistributedLockParam Long id) {
        Optional<Ticket> ticket = ticketRepository.findById(id);
        if (ticket.isPresent()) {
            Ticket ticket1 = ticket.get();
            if (ticket1.getTicketCount() > 0) {
                ticket1.setTicketCount(ticket1.getTicketCount() - 1);
                ticketRepository.save(ticket1);
                return ticket1.getTicketCount() + 1;
            } else {
                throw new RuntimeException("票已经卖完");
            }
        } else {
            throw new RuntimeException("票已经卖完");
        }
    }

}
